package com.demo2do.sms.listener;

import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.sms.Constant;
import com.demo2do.sms.rao.SmsRao;

public class SmsMessageListener implements MessageListener {
    
    private static final Logger logger = LoggerFactory.getLogger(SmsMessageListener.class);
    
    @Rao
    private SmsRao smsRao;
    
    /*
     * (non-Javadoc)
     * @see com.aliyun.openservices.ons.api.MessageListener#consume(com.aliyun.openservices.ons.api.Message, com.aliyun.openservices.ons.api.ConsumeContext)
     */
    public Action consume(Message message, ConsumeContext context) {
        
        logger.info("#consume() start consume message which body[{}], id[{}], topic[{}], tag[{}]", message.getBody(), message.getMsgID(), message.getTopic(), message.getTag());
        
        try {
            
            String tag = message.getTag();
            String messageString = new String(message.getBody(), StandardCharsets.UTF_8);
            
            logger.info("#consume() get tag[{}] messageString[{}]", tag, messageString);
            
            Map<String, Object> raoParams = JsonUtils.parse(messageString);
            HttpResult result = null;
            
            if (StringUtils.equalsIgnoreCase(tag, Constant.BATCH_SMS_TAG)) {
                
                logger.info("#consume() start call batch sms api");
                result = smsRao.batchSend(raoParams);
                logger.info("#consume() call batch sms api success, the result is [{}]", JsonUtils.toJson(result));
                
            } else if(StringUtils.equalsIgnoreCase(tag, Constant.SINGLE_SMS_TAG)) {
                
                logger.info("#consume() start call single sms api");
                result= smsRao.singleSend(raoParams);
                logger.info("#consume() call single sms api success, the result is [{}]", JsonUtils.toJson(result));
                
            }
            
            logger.info("#consume() success!");
            return Action.CommitMessage;
            
        }catch (Exception e) {
            
            logger.error("#consume() failed with errors:", e);
            return Action.ReconsumeLater;
        }
    }

}
